﻿namespace WinServiceManagerTool
{
    using Microsoft.Win32;
    using System;
    using System.ComponentModel;
    using System.Drawing;
    using System.Net;
    using System.ServiceModel;
    using System.ServiceProcess;
    using System.Windows.Forms;
    using System.Xml;

    public class Form1 : Form
    {
        private bool _isExit;
        private ServiceController _sc;
        private string _serviceName;
        private System.Windows.Forms.Timer _timerServiceState;
        private Button buttonClose;
        private Button buttonStart;
        private Button buttonStop;
        private IContainer components;
        private ContextMenuStrip contextMenuStrip1;
        private Label label1;
        private Label label3;
        private Label label4;
        private Label labelServiceName;
        private Label labelServiceState;
        private NotifyIcon notifyIcon1;
        private ServiceHost sh2;
        private TextBox textBoxAddr;
        private const string upgradeRootKeyName = @"SOFTWARE\HuaWeiSmartUpgrade\Service";
        private ToolStripMenuItem 启动服务ToolStripMenuItem;
        private ToolStripMenuItem 停止服务ToolStripMenuItem;
        private ToolStripMenuItem 退出ToolStripMenuItem;

        public Form1()
        {

            this._timerServiceState = null;
            this._sc = null;
            this._serviceName = "WCFService";
            this._isExit = false;
            this.sh2 = null;
            this.components = null;
            this.InitializeComponent();
            string str = "";
            string hostName = Dns.GetHostName();
            str = string.Format("http://{0}:8066/WCFService", hostName);
            this.textBoxAddr.Text = str;
            this._sc = new ServiceController(this._serviceName);
            this.RefreshServiceState();
            this._timerServiceState = new System.Windows.Forms.Timer();
            this._timerServiceState.Interval = 0x3e8;
            this._timerServiceState.Tick += new EventHandler(this._timer_Tick);
            this._timerServiceState.Start();
        }

        private void _timer_Tick(object sender, EventArgs e)
        {
            this.RefreshServiceState();
        }

        public static void AddAppInfoToRegistry(string url)
        {
            try
            {
                RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\HuaWeiSmartUpgrade\Service", true);
                if (key == null)
                {
                    key = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\HuaWeiSmartUpgrade\Service");
                }
                if (key != null)
                {
                    key.SetValue("ServiceAddress", url);
                }
            }
            catch
            {
            }
        }

        private void buttonClose_Click(object sender, EventArgs e)
        {
            base.Hide();
        }

        private void buttonStart_Click(object sender, EventArgs e)
        {
            this.SetWcfAddress(this.textBoxAddr.Text);
            AddAppInfoToRegistry(this.textBoxAddr.Text);
            if ((this._sc != null) && (this._sc.Status == ServiceControllerStatus.Stopped))
            {
                this.buttonStart.Enabled = false;
                this._sc.Start();
                this.RefreshServiceState();
            }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            if ((this._sc != null) && (this._sc.Status == ServiceControllerStatus.Running))
            {
                this.buttonStop.Enabled = false;
                this._sc.Stop();
                this.RefreshServiceState();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing && (this.components != null))
            {
                this.components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void Form1_Deactivate(object sender, EventArgs e)
        {
            if (base.WindowState == FormWindowState.Minimized)
            {
                base.Visible = false;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.WindowsShutDown)
            {
                base.Hide();
                if (!this._isExit)
                {
                    e.Cancel = true;
                }
            }
        }

        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
            this.buttonStart = new System.Windows.Forms.Button();
            this.buttonStop = new System.Windows.Forms.Button();
            this.buttonClose = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.labelServiceState = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.labelServiceName = new System.Windows.Forms.Label();
            this.label4 = new System.Windows.Forms.Label();
            this.textBoxAddr = new System.Windows.Forms.TextBox();
            this.notifyIcon1 = new System.Windows.Forms.NotifyIcon(this.components);
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.启动服务ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.停止服务ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.退出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.contextMenuStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // buttonStart
            // 
            this.buttonStart.Location = new System.Drawing.Point(97, 106);
            this.buttonStart.Name = "buttonStart";
            this.buttonStart.Size = new System.Drawing.Size(75, 23);
            this.buttonStart.TabIndex = 0;
            this.buttonStart.Text = "启动";
            this.buttonStart.UseVisualStyleBackColor = true;
            this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
            // 
            // buttonStop
            // 
            this.buttonStop.Location = new System.Drawing.Point(178, 106);
            this.buttonStop.Name = "buttonStop";
            this.buttonStop.Size = new System.Drawing.Size(75, 23);
            this.buttonStop.TabIndex = 0;
            this.buttonStop.Text = "停止";
            this.buttonStop.UseVisualStyleBackColor = true;
            this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
            // 
            // buttonClose
            // 
            this.buttonClose.Location = new System.Drawing.Point(259, 106);
            this.buttonClose.Name = "buttonClose";
            this.buttonClose.Size = new System.Drawing.Size(75, 23);
            this.buttonClose.TabIndex = 0;
            this.buttonClose.Text = "隐藏";
            this.buttonClose.UseVisualStyleBackColor = true;
            this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click);
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(22, 79);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(89, 12);
            this.label1.TabIndex = 1;
            this.label1.Text = "服务运行状态：";
            // 
            // labelServiceState
            // 
            this.labelServiceState.AutoSize = true;
            this.labelServiceState.Location = new System.Drawing.Point(117, 79);
            this.labelServiceState.Name = "labelServiceState";
            this.labelServiceState.Size = new System.Drawing.Size(41, 12);
            this.labelServiceState.TabIndex = 2;
            this.labelServiceState.Text = "已停止";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(22, 20);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(65, 12);
            this.label3.TabIndex = 4;
            this.label3.Text = "服务名称：";
            // 
            // labelServiceName
            // 
            this.labelServiceName.AutoSize = true;
            this.labelServiceName.Location = new System.Drawing.Point(113, 20);
            this.labelServiceName.Name = "labelServiceName";
            this.labelServiceName.Size = new System.Drawing.Size(65, 12);
            this.labelServiceName.TabIndex = 5;
            this.labelServiceName.Text = "服务器管理";
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(23, 50);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(65, 12);
            this.label4.TabIndex = 6;
            this.label4.Text = "服务地址：";
            // 
            // textBoxAddr
            // 
            this.textBoxAddr.Location = new System.Drawing.Point(115, 41);
            this.textBoxAddr.Name = "textBoxAddr";
            this.textBoxAddr.Size = new System.Drawing.Size(285, 21);
            this.textBoxAddr.TabIndex = 7;
            // 
            // notifyIcon1
            // 
            this.notifyIcon1.ContextMenuStrip = this.contextMenuStrip1;
            this.notifyIcon1.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon1.Icon")));
            this.notifyIcon1.Text = "大土木服务器监控程序";
            this.notifyIcon1.Visible = true;
            this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick);
            // 
            // contextMenuStrip1
            // 
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.启动服务ToolStripMenuItem,
            this.停止服务ToolStripMenuItem,
            this.退出ToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.Size = new System.Drawing.Size(125, 70);
            // 
            // 启动服务ToolStripMenuItem
            // 
            this.启动服务ToolStripMenuItem.Name = "启动服务ToolStripMenuItem";
            this.启动服务ToolStripMenuItem.Size = new System.Drawing.Size(124, 22);
            this.启动服务ToolStripMenuItem.Text = "启动服务";
            this.启动服务ToolStripMenuItem.Click += new System.EventHandler(this.启动服务ToolStripMenuItem_Click);
            // 
            // 停止服务ToolStripMenuItem
            // 
            this.停止服务ToolStripMenuItem.Name = "停止服务ToolStripMenuItem";
            this.停止服务ToolStripMenuItem.Size = new System.Drawing.Size(124, 22);
            this.停止服务ToolStripMenuItem.Text = "停止服务";
            this.停止服务ToolStripMenuItem.Click += new System.EventHandler(this.停止服务ToolStripMenuItem_Click);
            // 
            // 退出ToolStripMenuItem
            // 
            this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
            this.退出ToolStripMenuItem.Size = new System.Drawing.Size(124, 22);
            this.退出ToolStripMenuItem.Text = "退出";
            this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(412, 141);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.textBoxAddr);
            this.Controls.Add(this.label4);
            this.Controls.Add(this.labelServiceName);
            this.Controls.Add(this.buttonClose);
            this.Controls.Add(this.labelServiceState);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.buttonStart);
            this.Controls.Add(this.buttonStop);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "服务监控";
            this.Deactivate += new System.EventHandler(this.Form1_Deactivate);
            this.contextMenuStrip1.ResumeLayout(false);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            base.Show();
            base.WindowState = FormWindowState.Normal;
        }

        private string ReadWcfAddress()
        {
            try
            {
                string filename = AppDomain.CurrentDomain.BaseDirectory + "WinService.exe.config";
                XmlDocument document = new XmlDocument();
                document.Load(filename);
                return document.DocumentElement.SelectSingleNode("system.serviceModel/services/service/host/baseAddresses").LastChild.Attributes["baseAddress"].Value;
            }
            catch
            {
            }
            return null;
        }

        private void RefreshServiceState()
        {
            this._sc.Refresh();
            if (!this.ServiceIsExisted(this._serviceName))
            {
                this.labelServiceState.Text = "服务未安装";
                this.buttonStart.Enabled = false;
                this.buttonStop.Enabled = false;
                this.启动服务ToolStripMenuItem.Enabled = false;
                this.停止服务ToolStripMenuItem.Enabled = false;
            }
            else if (this._sc.Status == ServiceControllerStatus.Stopped)
            {
                this.labelServiceState.Text = "已停止";
                this.buttonStart.Enabled = true;
                this.buttonStop.Enabled = false;
                this.启动服务ToolStripMenuItem.Enabled = true;
                this.停止服务ToolStripMenuItem.Enabled = false;
                this.textBoxAddr.Enabled = true;
            }
            else if (this._sc.Status == ServiceControllerStatus.Running)
            {
                this.labelServiceState.Text = "已启动";
                this.buttonStart.Enabled = false;
                this.buttonStop.Enabled = true;
                this.启动服务ToolStripMenuItem.Enabled = false;
                this.停止服务ToolStripMenuItem.Enabled = true;
                this.textBoxAddr.Enabled = false;
            }
        }

        private bool ServiceIsExisted(string serviceName)
        {
            foreach (ServiceController controller in ServiceController.GetServices())
            {
                if (controller.ServiceName.ToLower() == serviceName.ToLower())
                {
                    return true;
                }
            }
            return false;
        }

        private void SetWcfAddress(string url)
        {
            try
            {
                string filename = AppDomain.CurrentDomain.BaseDirectory + "WinService.exe.config";
                XmlDocument document = new XmlDocument();
                document.Load(filename);
                document.DocumentElement.SelectSingleNode("system.serviceModel/services/service/host/baseAddresses").LastChild.Attributes["baseAddress"].Value = url;
                document.Save(filename);
            }
            catch
            {
            }
        }

        private void 启动服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.buttonStart_Click(null, null);
        }

        private void 停止服务ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.buttonStop_Click(null, null);
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this._timerServiceState != null)
            {
                this._timerServiceState.Stop();
            }
            this._isExit = true;
            base.Close();
        }
    }
}

